package com.xy.shop.web.service.impl;

import com.foxinmy.weixin4j.exception.WeixinException;
import com.xy.shop.common.constant.CommonContants;
import com.xy.shop.common.constant.Rst;
import com.xy.shop.web.entity.ApplyOrder;
import com.xy.shop.web.pay.WeixinDraw;
import com.xy.shop.web.service.ApplyOrderService;
import com.xy.shop.web.service.PayService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;
import java.util.Objects;

//@Transactional
@Service
public class PayServiceImpl implements PayService {

    @Value("${weixin.appid}")
    private   String appId ;

    @Value("${weixin.mchId}")
    private   String mchId  ;

    @Value("${weixin.mchKey}")
    private   String mchkey  ;

    @Value("${weixin.apiCert}")
    private   String cert ;

    public static Logger logger = LoggerFactory.getLogger(PayServiceImpl.class);

    @Resource
    private ApplyOrderService applyOrderService;
    @Override
    public Map<String, Object> redPacket() throws WeixinException {
        return null;
    }

    @Override
    public Map<String, Object> updateWxPayment(String orderId, String type) {
        ApplyOrder applyOrder= applyOrderService.selectByPrimaryKey(orderId);
        if (Objects.isNull(applyOrder)){
           return Rst.getReturnData(null,false,CommonContants.FAILURE,"订单不存在！");
        }
        if (applyOrder.getStatus() == 2){
            return Rst.getReturnData(null,false,CommonContants.FAILURE,"订单已支付！");
        }
        ApplyOrder updateOrder=new ApplyOrder ();
        int count ;
        //订单审核流程
        if(type .equals( "1")){
            if (applyOrder.getStatus() == 1){
                return Rst.getReturnData(null,false,CommonContants.FAILURE,"订单已经审核状态！");
            }
            updateOrder.setOrderId(orderId);
            updateOrder.setStatus(1);
            updateOrder.setAuditTime(new Date());
            count =applyOrderService.updateByPrimaryKey(updateOrder);
            if (count>0) {
                return Rst.getReturnData(null,true,CommonContants.FAILURE_SUCCESS,"订单修改成功！");
            }else {
                return Rst.getReturnData(null,false,CommonContants.FAILURE_1002,"订单审核失败！");
            }
        }
        //订单支付流程
        if(type .equals( "2")) {
            if (applyOrder.getStatus() != 1) {
                return Rst.getReturnData(null, false, CommonContants.FAILURE_1003, "订单非审核状态不能支付！");
            }
            if (StringUtils.isBlank(applyOrder.getOpenId())) {
                return Rst.getReturnData(null, false, CommonContants.FAILURE_1003, "当前用为收集到openId无法发放！");
            }
            if (Double.parseDouble(applyOrder.getMoney().toString()) < 1) {
                return Rst.getReturnData(null, false, CommonContants.FAILURE_1004, "支付金额必须1元，接口金额暂不支持！");
            }
            WeixinDraw weixinDraw = new WeixinDraw(appId, mchId, mchkey, cert);
            Map<String, String> map = weixinDraw.transfer(applyOrder.getOpenId(), (int) (applyOrder.getMoney().doubleValue() * 100), "订单返现", applyOrder.getOrderId());
            if (StringUtils.equals(map.get("state"), "SUCCESS")) {
                System.out.println("1:" + map.get("payment_no"));
                System.out.println("2:" + map.get("payment_time"));
                logger.debug("=============updateWxPayment==SUCCESS==openId" + applyOrder.getOpenId() + ":orderId: " + applyOrder.getOpenId()
                        + ":payment_no:" + map.get("payment_no") + ":payTime:" + map.get("payment_time"));
                logger.info("=============updateWxPayment==SUCCESS==openId" + applyOrder.getOpenId() + ":orderId: " + applyOrder.getOpenId()
                        + ":payment_no:" + map.get("payment_no") + ":payTime:" + map.get("payment_time"));
                /**更新db数据*/
                updateOrder.setOrderId(orderId);
                updateOrder.setStatus(2);
                updateOrder.setSendTime(new Date());
                updateOrder.setVxPayId(map.get("payment_no"));
                count = applyOrderService.updateByPrimaryKey(updateOrder);
                if (count > 0) {
                    return Rst.getReturnData(null, true, CommonContants.FAILURE_SUCCESS, "订单支付成功！");
                } else {
                    return Rst.getReturnData(null, false, CommonContants.FAILURE_1006, "订单支付失败！");
                }
            } else {
                logger.debug("=============updateWxPayment==err_code==" + map.get("err_code") + ":err_code_des:" + map.get("err_code_des"));
                logger.info("=============updateWxPayment==err_code==" + map.get("err_code") + ":err_code_des:" + map.get("err_code_des"));
                return Rst.getReturnData(null, false, CommonContants.FAILURE_1005, "支付失败！" + map.get("err_code") + "描述：" + map.get("err_code_des"));
            }
        }
        return Rst.getReturnData(null,false,CommonContants.FAILURE_1102,"支付失败！");
    }
}
